import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterstudyapplast/business/viewmodels/article_viewmodel.dart';
import 'package:flutterstudyapplast/services/service_locator.dart';
import 'package:provider/provider.dart';
import 'package:flutterstudyapplast/manager/app_manager.dart';
import 'package:flutterstudyapplast/common/event/events.dart';
import 'package:flutterstudyapplast/ui/page/page_webvew.dart';
import 'package:flutterstudyapplast/ui/widget/article_item.dart';
import 'package:flutterstudyapplast/ui/widget/banner_view.dart';
import 'package:flutterstudyapplast/ui/widget/main_drawer.dart';
import 'package:toast/toast.dart';

class ArticlePage extends StatefulWidget {

  @override
  _ArticlePageState createState() => _ArticlePageState();
}

class _ArticlePageState extends State<ArticlePage> {

  ScrollController _scrollController = new ScrollController();///滑动控制器
  bool isLoading = true;///是否在加载
  int curPage = 0;///当前页
  DateTime _lastClick;

  ArticleViewModel _articleViewModel = serviceLocator<ArticleViewModel>();
  

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController.addListener((){
      var maxScrollExtent = _scrollController.position.maxScrollExtent;///获得 SrollController 监听控件可以滚动的最大范围
      var pixels = _scrollController.position.pixels;///获得当前位置的像素值
      print("_articleViewModel:totalCount:$_articleViewModel.totalCount");
      if(pixels == maxScrollExtent && _articleViewModel.articles.length < _articleViewModel.totalCount){///滑动到底部并且有更多数据
        _getArticles();
      }
    });
    AppManager.eventBus.on<LoginEvent>().listen((event){
      ///页面没有被dispose
      if(mounted){
        setState(() {
          _pullToRefresh();
        });
      }
    });
    AppManager.eventBus.on<LoginOutEvent>().listen((event){
      ///页面没有被dispose
      if(mounted){
        setState(() {
          _pullToRefresh();
        });
      }
    });
    AppManager.eventBus.on<CollectEvent>().listen((event){
      ///页面没有被dispose
      if(mounted){
        _articleViewModel.articles.every((item){
          if(item.id == event.id){
            item.isCollect = event.isCollect;
            return false;
          }
        });
      }
    });
    _pullToRefresh();
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _scrollController?.dispose();
  }
  Future<void> _pullToRefresh() async{
    curPage = 0;
    Iterable<Future> futures = [_getArticles(),_getBanner()];
    await Future.wait(futures);
    isLoading = false;
    return null;
  }
  _getArticles([bool isUpdate = true]) async{
    _articleViewModel.loadData(curPage);
    curPage++;
  }
  _getBanner([bool isUpdate = true]) async{
    _articleViewModel.getBanner();
  }
  @override
  Widget build(BuildContext context) {
    return  ChangeNotifierProvider<ArticleViewModel>(
      create: (context) => _articleViewModel,
      child: Consumer<ArticleViewModel>(
        builder: (context,model,child) => WillPopScope(
          onWillPop: () async{
            //在一定的时间内 2s点击两次才能返回
            if (_lastClick == null ||
                DateTime.now().difference(_lastClick) > Duration(seconds: 2)) {
              _lastClick = DateTime.now();
              Toast.show("请再按一次退出!",context);
              return false;
            }
            return true;
          },
          child: Scaffold(
            appBar: AppBar(title: Text("文章")),
            drawer: MainDrawer(),
            drawerEdgeDragWidth: 100,
            body: Stack(
              children: <Widget>[
                Offstage(
                    offstage: !isLoading,
                    child: Center(child: CircularProgressIndicator())
                ),
                Offstage(
                    offstage: isLoading,
                    child: RefreshIndicator(
                      onRefresh: _pullToRefresh,
                      child: ListView.builder(
                          itemCount: model.articles.length+1,
                          itemBuilder: (context,index)=> _buildItem(index,model.articles,model.banners),
//                  itemCount: article.length+1,
//                  itemBuilder: (context,index)=> _buildItem(index,article),
                          controller: _scrollController
                      ),
                    )
                ),
                Offstage(
                  offstage: isLoading || model.articles.isNotEmpty,
                  child: Center(
                    child: InkWell(
                      onTap: (){
                        _pullToRefresh();
                        setState(() {
                          isLoading = true;
                        });
                      },
                      child: Text("点击重试"),
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      )
    ) ;
  }
  Widget _buildItem(int index,List articles,List banners){
    if(index == 0){
      return Container(
        height: MediaQuery.of(context).size.height * 0.3,
        child: _buildBanner(banners)
      );
    }
    var itemData = articles[index-1];
    return ArticleItem(itemData);
  }
  Widget _buildBanner(List banners){
    var items = banners.map((item){
      return InkWell(
        onTap: (){
          ///todo 跳转到webview\
          //Utils.openUrl(item['title'], item["url"]);
          //Utils.methodChannel.invokeMethod("openUrl",{"title":item['title'],"url":item["url"]});
          Navigator.push(context, MaterialPageRoute(builder: (_){
            return WebViewPage(item);
          }));
        },
        child: Image.network(item.imagePath,fit: BoxFit.cover)
      );
    }).toList();
    return items.isNotEmpty?BannerView(items,Duration(seconds: 3)):null;
  }
}
